<?php
error_reporting(1); 
include_once "SDB/sdb.php";
include_once "JSON/JSON.php";
include_once "S3/S3.php";
 
$access = "";
$secret = "";
$action = "";
$file = "";

function DeleteContent($filename, $ignore)
{
	if ($dh = opendir($filename))
	{
		while (($file = readdir($dh)) !== false) 
		{		
			if(!in_array(strtolower($file), $ignore)) 
			{
				unlink($filename."/".$file);
			}
		}
		rmdir($filename);
	}	
}

if(isset($_REQUEST["access"])) $access = $_REQUEST["access"];
if(isset($_REQUEST["secret"])) $secret = $_REQUEST["secret"];
if(isset($_REQUEST["action"])) $action = $_REQUEST["action"];
if(isset($_REQUEST["domain"])) $domain = $_REQUEST["domain"];
if(isset($_REQUEST["file"])) $file = $_REQUEST["file"];
if(isset($_REQUEST["restoreFile"])) $restoreFile = $_REQUEST["restoreFile"];

switch($action)
{
	case "domains":
		$sdb = new SimpleDB($access, $secret, true); 
		$s3 = new S3($access, $secret);
		$str = "";
		
		$arDomains = $sdb->listDomains();
		$er = $sdb->errorMessage["Errors"];
		
		if(count($er)>0)
		{
			foreach($er as $n=>$m)
			{
				$str.=$m["Message"]."\r\n";
			}
			echo $str;
			return;
		}
		
		$str .=@"<table style='width: 500px;' cellpadding='0' cellspacing='5'>";
		foreach($arDomains as $k=>$v){
			$str.= @"<tr>
					<td style='width: 350px;'>
						<a href='javascript:void(0);' >$v</a>
						<input type='hidden' value='$v' />
					</td>
					<td style='width: 50px;'>
						<!--<a href='javascript:void(0)' onclick='DeleteDomain(\"$v\", this)' >delete</a>-->
					</td>
					<td style='width: 80px;'>
						<a href='javascript:void(0)' onclick='BackupDomain(\"$v\", this)' >backup</a>
					</td>
					<td style='width: 20px;'>
						<img src='Content/ajax-loader.gif' alt='loading' style='display: none;' />
					</td>
				</tr>";
		}
		$str.= "</table>";
		echo $str;
		return;
	case "backup":
		
		$sdb = new SimpleDB($access, $secret, true); 
		$s3 = new S3($access, $secret, true);
		$json = new Services_JSON(SERVICES_JSON_LOOSE_TYPE);
		$meta = $sdb->domainMetadata($domain);
		
		$filename = dirname(__FILE__)."/Files/".$domain;
		
		//######################
		
		if (!file_exists($filename)) {  
			 mkdir($filename, 0777);
	    } 
	
		//######################
		
		$token = null;
		$fileHandle = null;
		$limit = 0;
		$fileCount = 0;
		for($j = 0; $j < $meta["ItemCount"]; $j += 100)
		{
			//####################
			
			if($j == 0 || $limit == 100)
			{
				$ourFileName = $filename."/". $domain."_".$fileCount.".js";
				$fileHandle = fopen($ourFileName, 'w') or die("can't open file");
				$limit = 0;
				$fileCount++;
			}
			
			//####################
			
			if($j == 0){
				$query = $sdb->select($domain, "select * from ".$domain." limit 100", null, false);
			}else{
				$token = $sdb->select($domain, "select * from ".$domain." limit 100", $token, true);
				$query = $sdb->select($domain, "select * from ".$domain." limit 100", $token, false);
			}
			foreach($query as $k_=>$v_)
			{
				$result = $json->encode($v_);
				fwrite($fileHandle, $result."\r\n");
			}
			
			$limit += 100;
		}
		fclose($fileHandle);
		
		$folder = $domain.".js";
		$exist = $s3->getBucket($domain);
		$ignore = array('.','..','.ds_store','.svn');
		if($exist == null)
		{
			$c = $s3->putBucket($domain, S3::ACL_PUBLIC_READ);
			if($c)
			{
				if ($dh = opendir($filename)){
					
					while (($file = readdir($dh)) !== false) {
						
						if(!in_array(strtolower($file), $ignore)) 
						{
							$f = $s3->putObjectFile($filename."/".$file, $domain, baseName($file), S3::ACL_PUBLIC_READ);
							if(!$f)
							{
								echo $s3->errorMessage["message"];
								DeleteContent($filename, $ignore);
								return;
							}
							
						}
					}
				}
			}else{
				echo $s3->errorMessage["message"];
				DeleteContent($filename, $ignore);
				return;	
			}	
		}else{
				if ($dh = opendir($filename))
				{
					while (($file = readdir($dh)) !== false) 
					{	
						if(!in_array(strtolower($file), $ignore)) 
						{
							$c_ = $s3->putObjectFile($filename."/".$file, $domain, baseName($file), S3::ACL_PUBLIC_READ);
							if(!$c_)
							{	
								echo $s3->errorMessage["message"];
								DeleteContent($filename, $ignore);
								return;
							}	
						}
					}
				}
		}
		
		DeleteContent($filename, $ignore);
		
		echo "true";
		return;
	case "restore":
		$sdb = new SimpleDB($access, $secret, true); 
		$s3 = new S3($access, $secret);
		$json = new Services_JSON(SERVICES_JSON_LOOSE_TYPE);
		$ignore = array('.','..','.ds_store','.svn');
		
		//$response = $s3->getBucket($file);
		
		//######################
		
		$filename = dirname(__FILE__)."/Files/".$file;
		if (!file_exists($filename)) {  
			mkdir($filename, 0777);
		} 
		
		//######################
		
		$cdomain = null;
		//foreach($response as $fileName=>$fileInfo){
		
		$str = "";
		$savedFile = $filename."/".$restoreFile;
		
		$res = $s3->getObject($file, baseName($savedFile), fopen($savedFile, 'wb'));
		$pathInfo = pathinfo($savedFile);
		
		$lastIndex = strrpos($pathInfo["filename"], "_");
		$cdomain_name = substr($pathInfo["filename"], 0, $lastIndex);
		
		if(!isset($cdomain))
		{
			$cdomain = $sdb->createDomain($cdomain_name);
		}
		
		$er = $sdb->errorMessage["Errors"];
		
		if(count($er) > 0)
		{
			foreach($er as $n=>$m)
			{
				$str.=$m["Message"]."\r\n";
			}
			
			echo "Error - ".$str;
			DeleteContent($filename, $ignore);
			return;
		}
		
		$lines = file($savedFile);
		
		$i = 0;
		foreach ($lines as $line_num => $line) {
			if(!isset($line)) continue;
			$ar = array();
			$ar = $json->decode($line);
			
			$arrValues = array();
			$itemValue = $ar["Name"];
			
			$vvv = array();
			$ii = 0;
			foreach($ar["Attributes"] as $n=>$vv)
			{
				$vvv[$n]["value"] = $vv;
			}
			
			$back = $sdb->putAttributes($cdomain_name, $itemValue, $vvv);
			if(!$back)
			{
				var_dump($sdb->errorMessage);
				return;
			}
			$i++;
		}
		
		unlink($savedFile);
		//}
		
		//DeleteContent($filename, $ignore);
		rmdir($filename);
		echo "true";
		return;
	case "files":
		$s3 = new S3($access, $secret);
		$files = $s3->listBuckets();
		$str = "";
		
		if($s3->errorMessage != false && count($s3->errorMessage) > 0)
		{
			echo $s3->errorMessage["message"];
			return;
		}
		
		$str .=@"<table style='width: 500px;' cellpadding='0' cellspacing='5'>";
		foreach($files as $k=>$v){
			
			$str.= @"<tr>
					<td style='width: 350px;'>
					
						<a href='javascript:void(0);' >$v</a>
						
					</td>
					<td style='width: 50px;'>
						<!--<a href='javascript:void(0)' onclick='DeleteFile(\"$v\", this)' >delete</a>-->
					</td>
					<td style='width: 80px;'>
						<!--<a href='javascript:void(0)' onclick='RestoreFile(\"$v\", this)' >restore</a>-->
					</td>
					<td style='width: 20px;'>
						<img src='Content/ajax-loader.gif' alt='loading' style='display: none;' />
					</td>
				</tr>";
				
				$response = $s3->getBucket($v);
			foreach($response as $fileName=>$fileInfo)
				{
					$str .= @"<tr>
							<td>&nbsp;&nbsp;&nbsp;<a href='javascript:void(0);' >$fileName</a></td>
							<td></td>
							<td><a href='javascript:void(0)' onclick='RestoreFile(\"$fileName\", this, \"$v\")' >restore</a></td>
							<td><img src='Content/ajax-loader.gif' alt='loading' style='display: none;' /></td>
						</tr>";
				}
		}
		$str.= "</table>";
		echo $str;
		return;
	case "delete_domain":
		
		break;
	
}

?>

<html>
	<head>
		<title>Simple db and S3 backup script</title>
		
		<script type="text/javascript" src="Content/jquery-1.4.2.min.js"></script>
		<script type="text/javascript">
		
		function BackupDomain(domain, btnId)
		{
			$(btnId).parent().parent().find("img").css({"display": "block"});
			if($("#access").val() == "" || $("#secret").val() == "")
			{
				alert('Please enter both keys!');
			}else{
				$.post("index.php", { access: $("#access").val(), secret: $("#secret").val(), action: "backup", domain: domain}, 
				function(data)
				{
					$(btnId).parent().parent().find("img").css({"display": "none"});
					if(data == "true")
					{
						
						alert("Backup created");	
					}else{
						alert(data);
					}
				});
			}
		}
		
		function RestoreFile(file, btnId, domain)
		{
			$(btnId).parent().parent().find("img").css({"display": "block"});
			if($("#access").val() == "" || $("#secret").val() == "")
			{
				alert('Please enter both keys!');
			}else{
				$.post("index.php", { access: $("#access").val(), secret: $("#secret").val(), action: "restore", file: domain, restoreFile: file}, 
				function(data)
				{
					$(btnId).parent().parent().find("img").css({"display": "none"});
					if(data == "true")
					{
						alert("Backup restored");	
					}else{
						alert(data);
					}
				});
			}
		}
		
		$(function()
		{
			$("#btnBackup").bind("click", function()
			{
				if($("#access").val() == "" || $("#secret").val() == "")
				{
					alert('Please enter both keys!');
				}else{
					$("#loading").css({"display": "block"});
					$.post("index.php", { access: $("#access").val(), secret: $("#secret").val(), action: "domains" }, 
					function(data)
					{
						$("#domains").html(data);
						$("#loading").css({"display": "none"});
					});
				}
			})
			
			$("#btnRestore").bind("click", function()
			{
				if($("#access").val() == "" || $("#secret").val() == "")
				{
					alert('Please enter both keys!');
				}else{
					$("#loading").css({"display": "block"});
					$.post("index.php", { access: $("#access").val(), secret: $("#secret").val(), action: "files" }, 
					function(data)
					{
						$("#domains").html(data);
						$("#loading").css({"display": "none"});
					});
				}
			})
			
		})
		
		</script>
		
		
	</head>
	<body>
		<table cellpadding="0" cellspacing="0" border="0" style="width: 500px;" >
			<tr>
				<td style="width: 100px;">
					Access key:
				</td>
				<td style="width: 400px">
					<input type="text" style="width: 400px;" id="access" />
				</td>
			</tr>
			<tr>
				<td>
					Secret key:
				</td>
				<td>
					<input type="text" style="width: 400px;" id="secret" />
				</td>
			</tr>
			<tr>
				<td colspan="2" style="text-align: right;">
					<input style="width: 100px;" type="button" id="btnBackup" value="Sdb domains" />&nbsp;&nbsp;&nbsp;
					<input style="width: 100px;" type="button" id="btnRestore" value="S3 files" />
				</td>
			</tr>
		</table>
		<br />
		<div id="loading" style="display: none; color: black; font-weight: bold;height: 15px; width: 200px;">please wait, loading....</div>
		<br />
		<div style="float: left; width: auto;" id="domains">
			
		</div>
	</body>
</html>